<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增模型</el-button>
        <!--        <el-button type="primary" @click="handleAddModel">添加模型</el-button>-->
        <!--        <el-button type="primary" @click="handleAddModel">删除模型</el-button>-->
<!--        <el-button type="primary" :icon="Upload" plain @click="batchAdd">批量添加模型</el-button>-->
<!--        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出模型数据</el-button>-->
        <el-button type="primary" plain @click="toModelInstanceDetail(scope)">模型实例详情页面</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope)">
          批量删除模型
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Refresh" @click="resetPass(scope.row)">训练</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <ModelDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="modelCenter">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { Model } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import ModelDrawer from "@/views/proTable/components/ModelDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh } from "@element-plus/icons-vue";
import { doTrain, getDModelList, addModel, updateModel, deleteModel } from "@/api/modules/new2";
import socket from "@/socket";  // 导入 socket.js

const router = useRouter();
const proTable = ref<ProTableInstance>();
const initParam = reactive({ type: 1 });

const toModelInstanceDetail = (scope) => {
  if (scope.selectedList.length === 1) {
    const modelId = scope.selectedList[0].modelId;
    router.push({ path: `/modelCenter/instance`, query: { 'modelId': modelId } });
  } else {
    ElNotification({
      title: "温馨提示",
      message: "请选择一条数据",
      type: "warning"
    });
  }
};

const dataCallback = (data: any) => {
  // console.log(data);
  return {
    list: data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return getDModelList(newParams);
};

const { BUTTONS } = useAuthButtons();

const columns = reactive<ColumnProps<Model.ResModelList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { type: "sort", label: "Sort", width: 80 },
  { type: "expand", label: "Expand", width: 85 },
  {
    prop: "modelId",
    label: "模型ID",
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}>
          {scope.row.modelId}
        </el-button>
      );
    }
  },
  {
    prop: "modelName",
    label: "模型名称",
    search: { el: "input", tooltip: "我是搜索提示" },
  },
  {
    prop: "entrain",
    label: "是否可训练",
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}>
          {scope.row.entrain}
        </el-button>
      );
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

const drawerRef = ref<InstanceType<typeof ModelDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Model.ResModelList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addModel : title === "编辑" ? updateModel : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};

const resetPass = async (params: Model.ResModelList) => {
  try {
    console.log('尝试连接到 Socket 服务器...');
    socket.connect();

    socket.on('connect', () => {
      console.log('Socket 连接成功');
    });

    socket.on('connect_error', (error) => {
      console.error('Socket 连接错误:', error);
    });

    socket.on('disconnect', (reason) => {
      console.log('Socket 断开连接:', reason);
    });

    console.log('开始调用 doTrain 函数进行训练...');
    await doTrain({
      modelId: params.modelId || 4,
      datasetId: params.datasetId || 10,
      params: {
        num_class: params.num_class || 39,
        learning_rate: params.learning_rate || 0.0001,
        dropout_rate: params.dropout_rate || 0.5
      }
    });

    socket.on('train_started', (data) => {
      console.log('监听到！train_started 事件:', data);
      ElMessage.success(`训练开始: ${data.message}`);
    });

    socket.on('train_progress', (data) => {
      console.log('训练进度:', data);
    });

    socket.on('train_ended', (data) => {
      console.log('监听到 train_ended 事件:', data);
      ElMessage.success(`训练结束: ${data.message}`);
      socket.disconnect();
    });

    socket.on('train_error', (data) => {
      console.log('监听到 train_error 事件:', data);
      ElMessage.error(`训练错误: ${data.message}`);
      socket.disconnect();
    });

    proTable.value?.getTableList();
  } catch (error) {
    console.error('训练模型过程中发生错误:', error);
    ElMessage.error('训练模型过程中发生错误');
  }
};

const deleteAccount = async (params: Model.ResModelList) => {
  await useHandleData(deleteModel, { modelId: [params.model_id] }, `删除【${params.model_name}】模型`);
  proTable.value?.getTableList();
};

const batchDelete = async (id: string[]) => {
  let modelId = id.map(item => item.modelId);
  await useHandleData(deleteModel, { modelId }, "删除所选模型信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};
</script>
